
import wx from 'weixin-js-sdk';

/**
 * 获取字符串长度，英文字符 长度1，中文字符长度2
 * @param {*} str
 */
export const getStrFullLength = (str = '') =>
  str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1
    }
    return pre + 2
  }, 0)

/**
 * 截取字符串，根据 maxLength 截取后返回
 * @param {*} str
 * @param {*} maxLength
 */
export const cutStrByFullLength = (str = '', maxLength) => {
  let showLength = 0
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      showLength += 1
    } else {
      showLength += 2
    }
    if (showLength <= maxLength) {
      return pre + cur
    }
    return pre
  }, '')
}

export const judgeEquipment = () => {
  let equipmentType = ""
  let agent = navigator.userAgent.toLowerCase()
  if(agent.match(/MicroMessenger/i)=="micromessenger") {
    wx.miniProgram.getEnv((res)=>{
      if (res.miniprogram) {
        equipmentType = "miniprogram"
      } else {
        equipmentType = "wxWeb"
      }
    })
  } else {
    let android = agent.indexOf("android")
    let iphone = agent.indexOf("iphone")
    let ipad = agent.indexOf("ipad")
    if(android != -1){
      equipmentType = "android"
    }
    if(iphone != -1 || ipad != -1){
      equipmentType = "ios"
    }
  }
  return equipmentType
}
// let topSpace = 0
// export const BodyScroll = (isState) => {
//   let bodyDoc = document.body
//   if (isState) {
//     topSpace = window.scrollY
//     bodyDoc.style.position = 'fixed'
//     bodyDoc.style.top = -topSpace + 'px'
//   } else {
//     bodyDoc .style.position = ''
//     bodyDoc .style.top = ''
//     window.scrollTo(0, topSpace ) // 回到原先位置
//   }
// }

export const getQueryVariable = (variable) => {
  let num = window.location.href.indexOf('?')
  let query = window.location.href.substr(num + 1)
  let vars = query.split("&");
  for (let i=0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if(pair[0] == variable){
      return pair[1];
    }
  }
  return(false);
}

export const debounce = (func, wait=1000) => {
  let timeout;
  return function(event){
   clearTimeout(timeout)
   timeout = setTimeout(()=>{
    func.call(this, event)
   },wait)
  }
 }
